<?php

namespace IDock\Insurance\LIHI\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\LIHI\LIHIEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllLIHIResponse
{
    //成功算价提示
    private $successTip = [
        '0001'
    ];

    public function resolve(): Response
    {
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return $this;
        }
        $data = json_decode($body, true);

        if ($this->printer and is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $resultCode = $data['result']['resultCode'] ?? '';
        $resultMess = trim($data['result']['resultMessage'] ?? '');
        //成功算价提示
        if (in_array($resultCode, $this->successTip) and ($data['result']['subPremium'] ?? '')) {

            $this->successTip = $resultMess;

            $this->setBody($data);
            return $this;
        }

        $this->successTip = false;

        if ($resultCode != '0' && strpos($resultMess, '重复投保') === false) {
            $this->setError($resultMess);
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;

    protected $records = [];

    protected $result = [];

    public $planCode = '';

    public $productCode = '';

    public $insuredNum = 1;

    public $renewalFlag;

    public function printerInit(): Response
    {
        if (!$this->printer->success) {
            return $this;
        }
        $body = $this->getBody()['result'] ?? [];
        $msg = $body['resultMessage'];
        $status = $body['status'] ?? '';
        if (!$status) {
            $this->repeat($msg, $body);//重复投保
            if ($this->printer->repeatInsuredFlg) {
                $this->printer->success = false;
                return $this;
            }
            $this->setError($msg);
        }

        if ($this->successTip) {
            $this->printer->repeatMessage = $this->successTip;
        }

        //询价流程号
        $this->printer->argc['flowId'] = $body['flowId'] ?? '';
        $mainData = $body['tprpTmainDto'] ?? [];

        //车船税
        if ($carShipTax = $body['prpTcarshipTaxDto'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax['sumTax'] ?? '';
            $this->printer->carTaxPrinter->overdue = $carShipTax['dealyPayPenylty'] ?? '';
            $this->printer->carTaxPrinter->thisYearTax = $carShipTax['vehicleTax'] ?? '';
        }

        $riskArr = $body['tprpTitemKindListDto'] ?? [];
        $biBasePremium = $biPremium = 0;
        foreach ($riskArr as $value) {
            if ($value['kindCodeMain'] == 'BZ') {
                //交强险
                $this->printer->ciPremiumPrinter->ciPremium = $value['premiumMain'] ?? '';
                $this->printer->ciPremiumPrinter->ciBasePremium = $value['benchMarkPremiumMain'] ?? '';
                $this->printer->ciPremiumPrinter->ciDiscount = $value['mtplDiscountMain'] ?? '';
                $startDate = $mainData['mtplStartDate'] ?? '';
                $this->printer->ciPremiumPrinter->ciStartData = mktime($mainData['mtplStartHour'] ?? '0', '0', '0', date('m', strtotime($startDate)), date('d', strtotime($startDate)), date('Y', strtotime($startDate)));
                $this->printer->ciPremiumPrinter->ciStartData = date('Y-m-d H:i:s', $this->printer->ciPremiumPrinter->ciStartData);
                $endDate = $mainData['mtplEndDate'] ?? '';
                $this->printer->ciPremiumPrinter->ciEndData = mktime($mainData['mtplEndHour'] ?? '', '0', '0', date('m', strtotime($endDate)), date('d', strtotime($endDate)), date('Y', strtotime($endDate)));
                $this->printer->ciPremiumPrinter->ciEndData = date('Y-m-d H:i:s', $this->printer->ciPremiumPrinter->ciEndData);
                $this->printer->ciInquiryNo = $mainData['mtplProposalNo'] ?? '';
                $ciFactor = $body['mtplPlatDto'] ?? [];
                $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险系数', 'rpaCause', $ciFactor['rpaCause'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('理赔调整系数', 'claimAdjustReasonValue', $ciFactor['claimAdjustReasonValue'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('理赔浮动原因', 'claimAdjustReason', $ciFactor['claimAdjustReason'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('违法浮动原因代码', 'peccancyAdjustReason', $ciFactor['peccancyAdjustReason'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('违法调整系数', 'peccancyAdjustReasonValue', $ciFactor['peccancyAdjustReasonValue'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('不浮动原因', 'rateFloatFlag', $ciFactor['rateFloatFlag'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('业务评分', 'pointNumber', $ciFactor['pointNumber'] ?? '');
                $this->printer->premiumFactorPrinter->TCIFactorAppend('分值等级', 'pointGrade', $ciFactor['pointGrade'] ?? '');
            } else {
                //商业险
                $biPremium += $value['premiumMain'] ?? 0;
                $biBasePremium += $value['benchMarkPremiumMain'] ?? 0;
            }
        }
        //商业险
        if ($biPremium > 0) {
            $this->printer->biPremiumPrinter = new PremiumBIPrinter();
            $this->printer->biPremiumPrinter->biPremium = $biPremium;
            $this->printer->biPremiumPrinter->biBasePremium = $biBasePremium;
            $biStartDate = $mainData['startDate'] ?? '';
            $this->printer->biPremiumPrinter->biStartData = mktime($mainData['startHour'] ?? '0', '0', '0', date('m', strtotime($biStartDate)), date('d', strtotime($biStartDate)), date('Y', strtotime($biStartDate)));
            $this->printer->biPremiumPrinter->biStartData = date('Y-m-d H:i:s', $this->printer->biPremiumPrinter->biStartData);
            $biEndDate = $mainData['endDate'] ?? '';
            $this->printer->biPremiumPrinter->biEndData = mktime($mainData['endHour'] ?? '0', '0', '0', date('m', strtotime($biEndDate)), date('d', strtotime($biEndDate)), date('Y', strtotime($biEndDate)));
            $this->printer->biPremiumPrinter->biEndData = date('Y-m-d H:i:s', $this->printer->biPremiumPrinter->biEndData);
            $this->printer->biPremiumPrinter->biDiscount = $mainData['discountMain'] ?? '';
            $this->printer->biInquiryNo = $mainData['proposalNo'] ?? '';
            $biFactor = $body['motorPlatDto'] ?? '';
            $this->printer->ncdFactor = $biFactor['claimAdjustReasonValue'] ?? '';

            //商业险系数
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优不浮动原因', 'noClaimAdjustReason', $biFactor['noClaimAdjustReason'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优调整系数', 'ncdRate', $biFactor['claimAdjustReasonValue'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('交通违法调整系数', 'peccancyAdjustReasonValue', $biFactor['peccancyAdjustReasonValue'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('交通违法浮动原因', 'peccancyAdjustReason', $biFactor['peccancyAdjustReason'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('交通违法不浮动原因', 'noPeccancyAdjustReason', $biFactor['noPeccancyAdjustReason'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('精准评分', 'score', $biFactor['score'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('业务评分', 'pointNumber', $biFactor['pointNumber'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('分值等级', 'pointGrade', $biFactor['pointGrade'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优系数级别', 'claimAdjustLevel', $mainData['claimAdjustLevel'] ?? '');
        }

        $this->printer->premiumFactorPrinter->ComFactorAppend('建议系数', 'autonomy', $mainData['autonomy'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('使用系数', 'autonomyValue', $mainData['autonomyValue'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('本次预估赔付率', 'lossedRate', $main['lossedRate'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('连续承保年数', 'insureYears', $main['insureYears'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('连续承保期间出险次数', 'claimTimes', $main['claimTimes'] ?? '');

        //续保类型
        $this->renewalFlag = $mainData['renewalFlag'] ?? '';

        //险种
        foreach ($riskArr as $kind) {
            if ($kind['kindCodeMain'] == 'BZ') {
                continue;
            }
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search($kind['kindCodeMain'] ?? '', LIHIEnums::$coverageCode);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode] ?? '';
            $coverage->premium = $kind['premiumMain'] ?? '';
            $coverage->basePremium = $kind['benchMarkPremiumMain'] ?? '';
            $coverage->amount = $kind['amountMain'] ?? '';
            $coverage->discount = $kind['discountMain'] ?? '';
            if (in_array($coverage->coverageCode, ['C08001', 'C08002', 'C08003', 'C08004', 'C18001', 'C18002', 'C18003', 'C18004'])) {
                $coverage->serviceTimes = $kind['quantityMain'] ?? '0';
            }
            $this->printer->coverageListAppend($coverage);
        }
        //特约
        $specialClause = $body['tprptEngageDTOList'] ?? [];
        foreach ($specialClause as $value) {
            $specialClauses = new SpecialClausesPrinter();
            $specialClauses->clauseCode = $value['clauseCode'] ?? '';
            $specialClauses->clauseName = $value['clausesName'] ?? '';
            $specialClauses->clauseContent = $value['clausesContext'] ?? '';
            if ($value['riskCode'] == '0502') {
                //商业险
                $specialClauses->riskType = 'VCI';
                $specialClauses->autoFlag = $value['mustFlag'] ? '0' : '1';
            } else {
                $specialClauses->riskType = 'TCI';
                $specialClauses->autoFlag = $value['mustFlag'] ? '0' : '1';
            }
            $this->printer->specialClausesAppend($specialClauses);
        }
        return $this;
    }

    /**
     * 重复投保
     * @param $message
     * @param $body
     */
    private function repeat($message, $body)
    {
        $ciStartData = $body['mtplPlatDto']['lastEndDate'] ?? '';
        $biStartData = $body['motorPlatDto']['lastEndDate'] ?? '';

        if ($ciStartData) {
            $ciStartData = date('Y-m-d H:i:s', strtotime($ciStartData));
            $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
            $this->printer->repeatInsuredFlg = true;
            $this->printer->repeatMessage = $message;
        }

        if ($biStartData) {
            $biStartData = date('Y-m-d H:i:s', strtotime($biStartData));
            $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
            $this->printer->repeatInsuredFlg = true;
            $this->printer->repeatMessage = $message;
        }
    }

    public function buildCoverage($isEnergy, array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as $coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }

            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }
    }

    private function setNonCarInfo($data)
    {
        $printer = new NonCarInquiryPrinter();
        $single = new NonCarInquirySinglePrinter();
        $single->productCode = $this->productCode;
        $single->planCode = $this->planCode;
        $single->inquiryNo = $data['subpolicyno'] ?? '';
        $printer->noCarInquirySingleAppend($single);
        $printer->totalPremium = $data['trialpremium'] ?? '0';
        $this->printer->nonCarInquiryPrinter = $printer;
    }

    /**
     * 续保标识
     * @param $licenseNo
     * @param $firstRegisterDate
     * @return void
     */
    public function renewalFlagType($licenseNo, $firstRegisterDate)
    {
        $renewalFlag = $this->renewalFlag;

        if (!strlen($renewalFlag)) {
            return;
        }
        //续保
        if ($renewalFlag == 1) {
            if ($this->printer->ciPremiumPrinter->ciPremium) {
                $this->printer->premiumFactorPrinter->ComFactorAppend('交强续保标识', 'CIRenewalType', '续');
            }
            if ($this->printer->biPremiumPrinter->biPremium) {
                $this->printer->premiumFactorPrinter->ComFactorAppend('商业续保标识', 'BIRenewalType', '续');
            }
        }

        //新保  转保
        if ($renewalFlag === '0') {
            $newCar = time() - strtotime($firstRegisterDate) < 60 * 60 * 24 * 30 * 3;
            if (!$licenseNo or $licenseNo == '新车' or $newCar) {
                if ($this->printer->ciPremiumPrinter->ciPremium) {
                    $this->printer->premiumFactorPrinter->ComFactorAppend('交强续保标识', 'CIRenewalType', '新');
                }
                if ($this->printer->biPremiumPrinter->biPremium) {
                    $this->printer->premiumFactorPrinter->ComFactorAppend('商业续保标识', 'BIRenewalType', '新');
                }
            } else {
                if ($this->printer->ciPremiumPrinter->ciPremium) {
                    $this->printer->premiumFactorPrinter->ComFactorAppend('交强续保标识', 'CIRenewalType', '转');
                }
                if ($this->printer->biPremiumPrinter->biPremium) {
                    $this->printer->premiumFactorPrinter->ComFactorAppend('商业续保标识', 'BIRenewalType', '转');
                }
            }
        }
    }
}
